package com.sunday.common.core.utils;

import java.io.*;

/**
 * 序列化
 *
 * @author zsy
 * @since 2022/10/12
 */
public class SerializationUtils {

    public static <T extends Serializable> T clone(final T object) {
        return (T) deserialize(serialize(object));
    }

    public static byte[] serialize(Object object) {
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos)) {
            oos.writeObject(object);
            oos.flush();
            return baos.toByteArray();
        } catch (IOException ex) {
            throw new RuntimeException("Failed to serialize object of type: " + object.getClass(), ex);
        }
    }

    public static Object deserialize(byte[] bytes) {
        try (ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes))) {
            return ois.readObject();
        } catch (IOException ex) {
            throw new RuntimeException("Failed to deserialize object", ex);
        } catch (ClassNotFoundException ex) {
            throw new RuntimeException("Failed to deserialize object type", ex);
        }
    }

}
